<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <!-- 新增按钮 -->
            <el-button type="primary" @click="showDialog=true"> + 新增角色</el-button>
            <!-- 角色表格 -->
            <el-table v-loading="loading" :data="roleList" border stripe class="myTable">
              <el-table-column label="序号" type="index" :index="indexMethod" width="120" />
              <el-table-column label="角色名称" prop="name" width="160" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template v-slot="{row}">
                  <el-button type="success" size="mini" @click="assignPermission(row.id)">分配权限</el-button>
                  <el-button type="primary" size="mini" @click="editRole(row.id)">编辑</el-button>
                  <el-button type="danger" size="mini" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 角色数据分页
              current-page: 当前页码值(现在在第几页)
              page-sizes: 每页可显示的页码个数列表
              page-size: 当页显示的每页数据条数
              layout: 分页组件布局
              total: 数据总条数

              @size-change:显示的数据条数发生改变时触发
              @current-change: 页码值改变时触发
             -->
            <el-pagination
              :current-page="page"
              :page-sizes="[2, 3, 5, 10]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="company">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form></el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 新增与编辑的弹出框 -->
      <el-dialog :title="showTitle" :visible="showDialog" @close="handleClose">
        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="clickSubmit">确认</el-button>
        </template>
      </el-dialog>

      <!-- 分配权限的弹出框 -->
      <el-dialog title="分配权限" :visible="showPermissionDialog" @open="handlePermissionOpen" @close="handlePermissionClose">
        <el-tree
          ref="tree"
          :data="permissionList"
          :props="{label:'name'}"
          show-checkbox
          default-expand-all
          check-strictly
          node-key="id"
        />
        <template #footer>
          <el-button @click="handlePermissionClose">取 消</el-button>
          <el-button type="primary" @click="clickRoleSubmit">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { reqGetRoleList, reqDelRole, reqAddRole, reqGetRoleDetail, reqUpdateRole, reqAssignPerm } from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { reqGetPermissionList } from '@/api/permission'
import { transListToTree } from '@/utils'
import { mapState } from 'vuex'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'role',

      page: 1,
      pagesize: 3,
      total: 0,

      roleList: [],

      loading: false,

      // 控制新增与编辑弹出框的显示与隐藏
      showDialog: false,

      // 控制分配权限弹出框的显示与隐藏
      showPermissionDialog: false,

      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ]
      },

      companyForm: {},

      permissionList: [],

      roleId: ''
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompany()
  },
  methods: {
    async getRoleList() {
      this.loading = true

      const { data: { rows, total }} = await reqGetRoleList(this.page, this.pagesize)
      this.roleList = rows
      this.total = total

      this.loading = false
    },
    // 显示的数据条数发生改变时触发
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.pagesize = newSize

      this.getRoleList()
    },
    // 页码值改变时触发
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.page = newPage

      this.getRoleList()
    },

    // 自定义序列号
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },

    // 删除角色
    async delRole(id) {
      const res = await this.$confirm('确定删除该角色吗', '提示').catch(error => error)
      if (res === 'cancel') return

      await reqDelRole(id)

      // 成功提示
      this.$message.success('删除角色成功')

      // 重新获取角色列表数据
      // 当页面只有一条数据时,删除完毕时,跳转到上一页
      if (this.roleList.length === 1 && this.page > 1) this.page--
      this.getRoleList()
    },

    // 关闭弹层
    handleClose() {
      this.showDialog = false

      this.$refs.roleForm.resetFields()

      this.form = {
        name: '',
        description: ''
      }
    },

    // 提交弹出框的数据
    clickSubmit() {
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return

        if (this.form.id) {
          // 编辑
          await reqUpdateRole(this.form)
          // 1.成功提示
          this.$message.success('更新角色成功')
        } else {
          // 新增
          await reqAddRole(this.form)
          // 1.成功提示
          this.$message.success('新增角色成功')
        }

        // 2.关闭弹层
        this.handleClose()

        // 3.获取角色列表
        this.getRoleList()
      })
    },

    // 编辑角色
    async editRole(id) {
      const res = await reqGetRoleDetail(id)
      this.form = res.data

      // 显示弹层
      this.showDialog = true
    },

    // 获取公司信息
    async getCompany() {
      const res = await reqGetCompanyById(this.userInfo.companyId)
      this.companyForm = res.data
    },

    // 1.获取所有的权限列表数据
    // 2.获取当前角色已有的数据(回填)
    // 3.修改权限后重新设置

    // 显示分配权限弹出框
    assignPermission(roleId) {
      this.roleId = roleId
      this.showPermissionDialog = true
    },

    // 关闭分配权限弹出框
    handlePermissionClose() {
      this.showPermissionDialog = false

      // 清空tree的所有的选中状态
      this.$refs.tree.setCheckedKeys([])
    },

    // 获取所有的权限列表
    async getPermissionList() {
      const { data } = await reqGetPermissionList()
      this.permissionList = transListToTree(data, '0')
    },

    // 根据角色id获取当前角色的权限
    async getRoleDeatil() {
      const { data: { permIds }} = await reqGetRoleDetail(this.roleId)
      this.$refs.tree.setCheckedKeys(permIds)
    },

    handlePermissionOpen() {
      this.getPermissionList()
      this.getRoleDeatil()
    },

    // 重新设置角色的权限
    async clickRoleSubmit() {
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      await reqAssignPerm({ id: this.roleId, permIds: checkedKeys })

      this.handlePermissionClose()
      this.$message.success('分配权限成功')
    }
  }
}
</script>

<style scoped lang="scss">
.myTable {
  margin:15px 0;
}
</style>
